package com.yunqing.restkeeper.web.common.response.interceptor;

import com.yunqing.restkeeper.common.tenant.TenantContext;
import com.yunqing.restkeeper.common.utils.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * @ClassName WebHandlerInterceptor
 * @Description TODO
 * @author: puyunqing
 * @Date: 2025/7/1
 */
@Slf4j
@Component
public class WebHandlerInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取 jwt
        String tokenInfo = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(tokenInfo)) {
            try {
                // 解析令牌
                Map<String, Object> tokenMap = JWTUtil.decode(tokenInfo);
                //String shopId = (String) tokenMap.get("shopId");

                // 将shopId存入 RPCContext
                //RpcContext.getServerContext().setAttachment("shopId", shopId);

                //将令牌Map放入自定义的上下文对象中
                TenantContext.addAttachments(tokenMap);

            } catch (Exception e) {
                log.error("解析令牌失败");
                e.printStackTrace();
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
